<template>
  <div class="Register">
    <shop-header> 注册 </shop-header>
    <logo></logo>
    <van-field
      v-model="usename"
      label="用户名"
      required
      :error-message="usenameMesErr"
      clearable
      placeholder="请输入用户名"
      @input="checkusename"
    />
    <van-field
      v-model="nickname"
      label="昵称"
      required
      :error-message="nicknameMesErr"
      clearable
      placeholder="请输入昵称"
      @input="checknickname"
    />
    <van-field
      v-model="password"
      type="password"
      label="密码"
      required
      :error-message="passwordMesErr"
      clearable
      placeholder="请输入密码"
      @input="checkpassword"
    />
    <shop-button @click.native="register">注册</shop-button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      usename: "",
      nickname: "",
      password: "",
      usenameMesErr: "",
      nicknameMesErr: "",
      passwordMesErr: "",
    };
  },
  methods: {
    checkusename() {
      if (this.usename == "") {
        this.usenameMesErr = "";
      } else {
        const reg = /^1\d{3,5}$/;
        if (reg.test(this.usename)) {
          this.usenameMesErr = "";
        } else {
          this.usenameMesErr = "用户名格式不正确";
        }
      }
    },
    checknickname() {
      if (this.nickname == "") {
        this.nicknameMesErr = "";
      } else {
        const reg = /^[\u4e00-\u9fa5]{2,3}$/;
        if (reg.test(this.nickname)) {
          this.nicknameMesErr = "";
        } else {
          this.nicknameMesErr = "昵称格式不正确";
        }
      }
    },
    checkpassword() {
      if (this.password == "") {
        this.passwordMesErr = "";
      } else {
        const reg = /^[a-z0-9]{6,11}$/;
        if (reg.test(this.password)) {
          this.passwordMesErr = "";
        } else {
          this.passwordMesErr = "密码格式不正确";
        }
      }
    },
    async register() {
      if (
        this.usename !== "" &&
        this.nickname !== "" &&
        this.password !== "" &&
        this.usenameMesErr == "" &&
        this.nicknameMesErr == "" &&
        this.passwordMesErr == ""
      ) {
        const res = await this.$axios.post("/register", {
          username: this.usename,
          password: this.password,
          nickname: this.nickname,
        });
        const { message, statusCode } = res.data;
        console.log(message, statusCode);
        if (statusCode == 200) {
          this.$router.push({
            name: "login",
            params: {
              usename: this.usename,
              password: this.password,
            },
          });
        } else {
          this.$toast(message);
        }
      } else {
        this.$toast.fail("注册信息不通过");
      }
    },
  },
};
</script>

<style></style>
